<?php
include('../resource/db/db.php');
$pageTitle = "学习盒子";
$currentPage = "box";

if (!isset($_COOKIE['user_id'])) {
    header("Location: ../main/login.php");
    exit();
}

$user_id = $_COOKIE['user_id'];

$sql = "SELECT study_records.record_id, cards.title, study_records.next_review, study_records.box_number 
        FROM study_records 
        JOIN cards ON study_records.card_id = cards.card_id 
        WHERE study_records.user_id='$user_id' AND study_records.is_deleted=FALSE AND cards.is_deleted=FALSE";
$result = $conn->query($sql);

function getBoxTitle($days_diff) {
    if ($days_diff == 0) {
        return "今天";
    } elseif ($days_diff == 1) {
        return "明天";
    } elseif ($days_diff == 7) {
        return "一周后";
    } elseif ($days_diff == 14) {
        return "十四天后";
    } elseif ($days_diff == 30) {
        return "一个月后";
    } else {
        return "永恒";
    }
}

function getDaysDiff($next_review) {
    $now = new DateTime();
    $next_review_date = new DateTime($next_review);
    $interval = $now->diff($next_review_date);
    return (int)$interval->format('%a');
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>学习盒子</title>
    <link rel="stylesheet" href="../resource/css/styles.css">
</head>
<body>
    <?php include('../resource/navbar.php'); ?>
    <div class="container">
        <h2>您的学习盒子</h2>
        <div class="box-container">
            <?php
            $boxes = [];
            if ($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                    $days_diff = getDaysDiff($row['next_review']);
                    $boxTitle = getBoxTitle($days_diff);
                    if (!isset($boxes[$boxTitle])) {
                        $boxes[$boxTitle] = [];
                    }
                    $boxes[$boxTitle][] = $row;
                }

                foreach ($boxes as $boxTitle => $cards) {
                    echo "<div class='box-title'>$boxTitle</div>";
                    foreach ($cards as $card) {
                        echo "<a href='review.php?record_id=" . $card['record_id'] . "' class='box-link'>";
                        echo "<div class='card'>" . $card['title'] . "</div>";
                        echo "</a>";
                    }
                }
            } else {
                echo "没有找到学习记录。";
            }
            ?>
        </div>
    </div>
</body>
</html>
